package cn.clx.ymcc.rocketmq;

import cn.clx.ymcc.constants.BaseConstant;
import cn.clx.ymcc.domain.Course;
import cn.clx.ymcc.domain.MessageEmail;
import cn.clx.ymcc.domain.MessageSms;
import cn.clx.ymcc.domain.MessageStation;
import cn.clx.ymcc.service.IMessageEmailService;
import cn.clx.ymcc.service.IMessageSmsService;
import cn.clx.ymcc.service.IMessageStationService;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 课程上架，异步消息，消费者
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "course-topic-push",
        selectorExpression="course-tags-push"	//tags
                ,consumerGroup = "service-common-emailmessage-consumer")
public class CourseMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageEmailService messageEmailService;
    @Autowired
    private IMessageSmsService messageSmsService;
    @Autowired
    private IMessageStationService messageStationService;


    @Override
    @Transactional
    public void onMessage(MessageExt message) {
        String msg = new String(message.getBody(), CharsetUtil.UTF_8);
        Course course = JSONObject.parseObject(msg,Course.class);
        //保存数据
        MessageEmail messageEmail = new MessageEmail();
        messageEmail.setTitle(BaseConstant.CourseConstants.COURSE_ONLINE_TITLE);
        String messEmail="亲爱的用户您好，最新课程 <a href='"+course.getName()+"'> "+course.getName()+" </a> 发布啦，点击课程了解详情";
        messageEmail.setContent(messEmail);
        messageEmail.setSendTime(new Date());
        messageEmail.setUserId(1l);
        messageEmailService.insert(messageEmail);
        //发送短信消息 应该是给全部的用户发送短信，1查找出全部的用户 循环保存 发送邮件消息给用户邮件
        log.info(messEmail);

        MessageSms messageSms = new MessageSms();
        messageSms.setTitle(BaseConstant.CourseConstants.COURSE_ONLINE_TITLE_NOTICE);
        messageSms.setContent(messEmail);
        messageSms.setUserId(1l);
        messageSms.setSendTime(new Date());
        messageSmsService.insert(messageSms);

        MessageStation messageStation = new MessageStation();
        messageStation.setContent(messEmail);
        messageStation.setTitle(BaseConstant.CourseConstants.COURSE_ONLINE_TITLE);
        messageStation.setType(BaseConstant.CourseConstants.COURSE_ONLINE_YPTE);
        messageStation.setSendTime(new Date());
        messageEmail.setUserId(1l);
        messageStationService.insert(messageStation);


    }
}